
var logList = new Array(10);
var uartOneLine = "";
var deviceID="";
var deviceSecret="";
var imei="";
var ser = null;

function DeviceSecretAutoGen()
{
    var t = new Date().getTime();
    var m = md5(t);
    return m.slice(0, -1);
}

function getOs()  
{  
    var OsObject = "";  
    if(navigator.userAgent.indexOf("MSIE")>0) {  
        return "MSIE";  //ie浏览器
    }  
    if(isFirefox=navigator.userAgent.indexOf("Firefox")>0){  
        return "Firefox";  //Firefox浏览器
    }  
    if(isSafari=navigator.userAgent.indexOf("Safari")>0) {  
        return "Safari";  //Safari浏览器
    }   
    if(isCamino=navigator.userAgent.indexOf("Camino")>0){  
        return "Camino";  //Camino浏览器
    //……增加一些其它代码……
    }  
    if(isMozilla=navigator.userAgent.indexOf("Gecko/")>0){  
        return "Gecko";  
    }  
} 

function processUartOneLine(oneLine)
{
    if(oneLine.charCodeAt(0) == 0x0D || oneLine.charCodeAt(0) == 0x0A)
        oneLine = oneLine.substr(1)
    if(oneLine.charCodeAt(0) == 0x0D || oneLine.charCodeAt(0) == 0x0A)
        oneLine = oneLine.substr(1)
        
    //console.log(oneLine)
    if (oneLine.length > 13)
    var c0 = oneLine.charCodeAt(0);
    var c1 = oneLine.charCodeAt(1);
    var c2 = oneLine.charCodeAt(2);
    var c3 = oneLine.charCodeAt(3);
    var c4 = oneLine.charCodeAt(4);
    var c5 = oneLine.charCodeAt(5);
    var c6 = oneLine.charCodeAt(6);
    if (c0 == 0x1B && c1 == 0x5B && c3 == 0x3B && c6 == 0x6D)
        oneLine = oneLine.substr(7)
    if(oneLine.charCodeAt(oneLine.length-1) == 0x0D || oneLine.charCodeAt(oneLine.length-1) == 0x0A)
        oneLine = oneLine.substr(0, oneLine.length-1)
    if(oneLine.charCodeAt(oneLine.length-1) == 0x0D || oneLine.charCodeAt(oneLine.length-1) == 0x0A)
        oneLine = oneLine.substr(0, oneLine.length-1)
    var cb0 = oneLine.charCodeAt(oneLine.length-1);
    var cb1 = oneLine.charCodeAt(oneLine.length-2);
    var cb2 = oneLine.charCodeAt(oneLine.length-3);
    var cb3 = oneLine.charCodeAt(oneLine.length-4);
    if (cb0 == 0x6D && cb1 == 0x30 && cb2 == 0x5B && cb3 == 0x1B)
        oneLine = oneLine.substr(0, oneLine.length-4)
    
    if(oneLine.length > 0)
        console.log(oneLine)
    return oneLine;
}

var uartRecvPreFnc = processUartOneLine;
var uartRecvPostFnc = null;

function appendData(bytes, size)
{
    for(var i=0;i<size;++i)
    {
        uartOneLine += String.fromCharCode(bytes[i]);
        if(bytes[i]== 0x0A) {
            var postLine = uartRecvPreFnc(uartOneLine)
            if (postLine && uartRecvPostFnc) {
                uartRecvPostFnc(postLine);
            }
            uartOneLine = "";
        }
    }
}

function recv(bytes, size)
{
    appendData(bytes, size)
}
    
function uartSendBuff(buff) {
    for (var i = 0; i < buff.length; i++) {
        ser.send(buff.charCodeAt(i));
    }
}

function FindDeviceInfo(line)
{
    var i;
    line.trim();
    //I (989760) sim800c: GSN:869286030783125
    i = line.indexOf("GSN:");
    if (i > 0) {
        $("#DeviceIMEI").val(line.slice(i+4))
    }
    //I (3315140) factory: Device ID = test6666
    i = line.indexOf("Device ID = ");
    if (i > 0) {
        $("#DeviceSN").val(line.slice(i+12))
    }
    //I (3315170) factory: Device Secret = test6666
    i = line.indexOf("Device Secret = ");
    if (i > 0) {
        $("#DeviceSecret").val(line.slice(i+16))
    }
}

function DeviceRead()
{
    $("#DeviceIMEI").val("");
    $("#DeviceSN").val("");
    $("#DeviceSecret").val("");
    $("#DeviceDID").val("");
    uartRecvPostFnc = FindDeviceInfo;
    uartSendBuff("imei\n");
    uartSendBuff("deviceid\n");
    uartSendBuff("devicesecret\n");
}

function DeviceInit()
{
    $("#DeviceSecret").val(DeviceSecretAutoGen())
    uartRecvPostFnc = null;
}

function DeviceSaveSuccessFnc(dat)
{
    dat = dat.replace(/\s*/g,"");
    var parser=new DOMParser(); 
    var x = $('<div/>').html(dat).text();
    var xmlDoc=parser.parseFromString(x,"text/xml"); 
    console.log(xmlDoc);
    var xNode=xmlDoc.getElementsByTagName("NewDataSet")[0].childNodes;
    console.log(xNode);
    alert(xNode[0].getElementsByTagName("id")[0].firstChild.nodeValue);
    uartRecvPostFnc = null;
    uartSendBuff("deviceid " + $("#DeviceSN").val() + "\n");
    uartSendBuff("devicesecret " + $("#DeviceSecret").val() + "\n");
}

function DeviceSaveFailFnc(XMLHttpRequest, textStatus, errorThrown)
{
    // 状态码
    console.log(XMLHttpRequest.status);
    // 状态
    console.log(XMLHttpRequest.readyState);
    // 错误信息   
    console.log(textStatus);
    alert("Call AddDeivceV2 error!return:"+XMLHttpRequest.status);
}

function DeviceSave()
{
    alert("DeviceSave");
    var token, imei, sn, secret, simn, phonen, did;
    //token = "B65117DF38AB05F13601FFAB56E4D1A5";
    token = $.cookie("token");
    imei = $("#DeviceIMEI").val();
    sn = $("#DeviceSN").val();
    secret = $("#DeviceSecret").val();
    simn = "";
    phonen = "";
    did = $("#DeviceDID").val();
    if (sn.length > 0 && secret.length > 0 && did.length > 0) {
        AddDeviceV2(token, imei, sn, secret, simn, phonen,did,DeviceSaveSuccessFnc,DeviceSaveFailFnc);
    }else{
        alert("请输入设备号，设备secret以及设备ID");
    }

}

function uartOpen()
{
    var s = ser.open("COM5");// Open a port
    if (s) {
        ser.set_option(115200,0,8,0,0);// Set port options 
        ser.recv_callback(recv); // Callback function for recieve data
        $("#DeviceIMEI").val("");
        $("#DeviceSN").val("");
        $("#DeviceSecret").val("");
        $("#DeviceDID").val("");
        $("#DeviceRead").click(DeviceRead);
        $("#DeviceInit").click(DeviceInit);
        $("#DeviceSave").click(DeviceSave);
        return 0;
    }
    return 1;
}

function uartClose()
{
    if(ser) {
        ser.close()
        $("#DeviceInit").unbind("click");
        $("#DeviceSave").unbind("click");
    }
    return 0;
}

function plugin0()
{
    return document.getElementById('plugin0');
}
plugin = plugin0;

function pluginLoaded() 
{
    if (getOs() != "Firefox")
    {
        alert("您的浏览器不支持:"+getOs());
    }else{
        ser = plugin().Serial;// Get a Serial object
        if(ser != null) {
            var ports = ser.getports()
            for (i in ports) {
                $("#ComPortList").append("<option value=\"" + ports[i] + "\">" + ports[i] + "</option>");
            }
            $("#ComPortOpen").click(function(){
                if ($("#ComPortOpen").text() == "打开") {
                    if (uartOpen() == 0) $("#ComPortOpen").text("关闭");
                }else{
                    if (uartClose() == 0) $("#ComPortOpen").text("打开");
                }
            });
        }
    }
}

function pluginValid()
{
    if(plugin().valid){
    alert(plugin().echo("This plugin seems to be working!"));
    } else {
    alert("Plugin is not working :(");
    }
}
function sendData() {
    var s = document.getElementById("command");
    if (s.value) {
        uartSendBuff(s.value+"\n");
    }
}
